import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './user.entity';
import { CasbinService } from '../casbin/casbin.service';
import { CasbinRoleService } from '../casbin/casbin-role.service';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private userRepository: Repository<User>,
    private casbinService: CasbinService,
    private casbinRoleService: CasbinRoleService,
  ) {}

  async findAll(): Promise<User[]> {
    return await this.userRepository.find();
  }

  async findOne(id: number): Promise<User | null> {
    return await this.userRepository.findOne({ where: { id } });
  }

  async findByUsername(username: string): Promise<User | null> {
    return await this.userRepository.findOne({ where: { username } });
  }

  async create(userData: Partial<User>): Promise<User> {
    const user = this.userRepository.create(userData);
    return await this.userRepository.save(user);
  }

  async update(id: number, userData: Partial<User>): Promise<User | null> {
    await this.userRepository.update(id, userData);
    return await this.userRepository.findOne({ where: { id } });
  }

  async remove(id: number): Promise<void> {
    await this.userRepository.delete(id);
  }

  // 为用户分配角色
  async assignRoleToUser(username: string, roleName: string): Promise<boolean> {
    return await this.casbinRoleService.assignRoleToUser(username, roleName);
  }

  // 获取用户的角色
  async getUserRoles(username: string): Promise<string[]> {
    return await this.casbinRoleService.getUserRoles(username);
  }

  // 删除用户的角色
  async removeRoleFromUser(username: string, roleName: string): Promise<boolean> {
    return await this.casbinRoleService.removeRoleFromUser(username, roleName);
  }
}